package zzti.edu.cn.generic.generi.goods;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;





public class GoodsManagerImpl implements GoodsManager{
	protected Logger logger = LogManager.getLogger(this.getClass().getName());
	List<Goods> goodsList;
	Map<String, Goods> goodsMap;
	Map<Long, Goods> goodsIdMap;
	
	public void load(String data_file) {
		this.goodsList=new ArrayList<Goods>();
		this.goodsMap = new HashMap<String, Goods>();
		this.goodsIdMap = new HashMap<>();
		InputStream input =GoodsManagerImpl.class.getResourceAsStream(data_file);
		XSSFWorkbook wb=null;
		try {
			wb = new XSSFWorkbook(input);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		XSSFSheet sheet = wb.getSheetAt(1);
		for (int i = 1; i <=sheet.getLastRowNum() ; i++) {
			Row row = sheet.getRow(i);
			Goods s = new Goods();
			s.setId(Long.valueOf(1000 + i));
			for (int j = 0; j <= row.getLastCellNum(); j++) {
				Cell cell = row.getCell(j);
				if (cell != null) {
					cell.setCellType(CellType.STRING);
					String value = row.getCell(j).getStringCellValue().trim();
					if (j == 0)
						s.setName(value);
					if (j == 1)
						s.setPrice(value);
					if (j == 2)
						s.setSales(value);
				}
			}
			logger.info(" goods_" + i + " is :" + s);
		
			this.goodsList.add(s);
			this.goodsMap.put(s.getName(), s);
			this.goodsIdMap.put(s.getId(), s);
		}
		logger.info("size of goods list is :" + this.goodsList.size());
	}

	public List<Goods> findByName(String name) {
		return  ((GoodsManagerImpl) this.goodsMap).findByName(name);
	}

	public Goods findbyId(Long id) {
		return this.goodsIdMap.get(id);
	}


}
